package ahu.zdw.com;

import java.util.Arrays;

/**
 * Author: Zhang Dongwei
 * Date: 2022/3/6 21:19
 */
public class _26_RemoveDuplicates {
    public static void main(String[] args) {
        Solution1 solution = new _26_RemoveDuplicates().new Solution1();
        int[] a = {1, 2, 2, 2, 3};
        int res = solution.removeDuplicates(a);
        System.out.println(res);
    }

//    自己写的，但是占用内存过高，速度有时快有时慢
    class Solution {
        public int removeDuplicates(int[] nums) {
            int i;
            int j = 0;
            for (i = 0; i < nums.length; i++) {
                nums[i-j] = nums[i];
                if(i < nums.length-1 && nums[i]==nums[i+1]){
                    j += 1;
                }
            }
            return i-j;
        }
    }
//  官方给的答案
    class Solution1 {
        public int removeDuplicates(int[] nums) {
            int n = nums.length;
            if (n == 0) {
                return 0;
            }
            int fast = 1, slow = 1;
            while (fast < n) {
                if (nums[fast] != nums[fast - 1]) {
                    nums[slow] = nums[fast];
                    ++slow;
                }
                ++fast;
            }
            return slow;
        }
    }
}
